"""
元数据提取插件

提供元数据提取功能的插件实现。
"""

from typing import Dict, List, Any, Optional
import logging

from src.core.plugin import Plugin
from src.core.di import Inject
from src.services.metadata_service import MetadataService
from src.modules.extractors import VideoMetadata, AudioMetadata


class MetadataPlugin(Plugin):
    """
    元数据提取插件
    
    提供视频和音频文件的元数据提取功能。
    """
    
    def __init__(self,
                 metadata_service: MetadataService = None,
                 config: Dict[str, Any] = None,
                 logger: logging.Logger = None):
        super().__init__()

        # 如果没有提供依赖，尝试从依赖注入容器获取
        if metadata_service is None:
            from src.bootstrap import get_service
            self.metadata_service = get_service(MetadataService)
        else:
            self.metadata_service = metadata_service

        if config is None:
            from src.bootstrap import get_service
            from src.services.config_service import ConfigService
            config_service = get_service(ConfigService)
            self.config = config_service.get_all()
        else:
            self.config = config

        if logger is None:
            import logging
            self.logger = logging.getLogger("MetadataPlugin")
        else:
            self.logger = logger
    
    @property
    def name(self) -> str:
        return "metadata_plugin"
    
    @property
    def version(self) -> str:
        return "1.0.0"
    
    @property
    def description(self) -> str:
        return "元数据提取插件，支持视频和音频文件的详细元数据提取"
    
    @property
    def author(self) -> str:
        return "MixVideo Team"
    
    def get_supported_operations(self) -> List[str]:
        return [
            "extract_metadata",
            "batch_extract",
            "analyze_directory",
            "compare_files",
            "export_metadata"
        ]
    
    def get_metadata(self) -> Dict[str, Any]:
        return {
            "name": self.name,
            "version": self.version,
            "description": self.description,
            "author": self.author,
            "supported_operations": self.get_supported_operations(),
            "supported_formats": [
                "mp4", "avi", "mov", "mkv", "webm", "flv", "wmv", "m4v",
                "mp3", "wav", "aac", "flac", "ogg", "wma", "m4a"
            ],
            "features": [
                "FFmpeg元数据提取",
                "OpenCV视觉特征提取",
                "复合元数据提取",
                "批量处理",
                "缓存机制",
                "多格式导出"
            ]
        }
    
    async def initialize(self) -> bool:
        """初始化插件"""
        try:
            
            # 测试服务可用性
            test_result = await self._test_service()
            if not test_result:
                self.logger.error("元数据服务测试失败")
                return False
            
            return True
            
        except Exception as e:
            self.logger.error(f"元数据提取插件初始化失败: {e}")
            return False
    
    async def cleanup(self) -> None:
        """清理插件资源"""
        self.logger.info("清理元数据提取插件资源")
    
    async def process(self, input_data: Any, operation: str = "extract_metadata", **kwargs) -> Any:
        """
        处理数据
        
        Args:
            input_data: 输入数据
            operation: 操作类型
            **kwargs: 其他参数
        
        Returns:
            处理结果
        """
        try:
            if operation == "extract_metadata":
                return await self._extract_metadata(input_data, **kwargs)
            elif operation == "batch_extract":
                return await self._batch_extract(input_data, **kwargs)
            elif operation == "analyze_directory":
                return await self._analyze_directory(input_data, **kwargs)
            elif operation == "compare_files":
                return await self._compare_files(input_data, **kwargs)
            elif operation == "export_metadata":
                return await self._export_metadata(input_data, **kwargs)
            else:
                raise ValueError(f"不支持的操作类型: {operation}")
                
        except Exception as e:
            self.logger.error(f"元数据提取插件处理失败: {e}")
            raise
    
    async def _extract_metadata(self, file_path: str, **kwargs) -> Dict[str, Any]:
        """提取单个文件的元数据"""
        self.logger.info(f"提取元数据: {file_path}")
        
        metadata = await self.metadata_service.extract_metadata(file_path, **kwargs)
        
        return {
            "success": True,
            "file_path": file_path,
            "metadata": metadata.to_dict(),
            "metadata_type": "video" if isinstance(metadata, VideoMetadata) else "audio"
        }
    
    async def _batch_extract(self, file_paths: List[str], **kwargs) -> Dict[str, Any]:
        """批量提取元数据"""
        self.logger.info(f"批量提取 {len(file_paths)} 个文件的元数据")
        
        results = await self.metadata_service.batch_extract_metadata(file_paths, **kwargs)
        
        # 转换结果格式
        processed_results = {}
        success_count = 0
        
        for file_path, metadata in results.items():
            if metadata:
                processed_results[file_path] = {
                    "success": True,
                    "metadata": metadata.to_dict(),
                    "metadata_type": "video" if isinstance(metadata, VideoMetadata) else "audio"
                }
                success_count += 1
            else:
                processed_results[file_path] = {
                    "success": False,
                    "error": "元数据提取失败"
                }
        
        return {
            "success": True,
            "total_files": len(file_paths),
            "success_count": success_count,
            "results": processed_results
        }
    
    async def _analyze_directory(self, directory: str, **kwargs) -> Dict[str, Any]:
        """分析目录"""
        self.logger.info(f"分析目录: {directory}")
        
        analysis = await self.metadata_service.analyze_directory(directory, **kwargs)
        
        return {
            "success": True,
            "analysis": analysis
        }
    
    async def _compare_files(self, file_paths: List[str], **kwargs) -> Dict[str, Any]:
        """比较文件"""
        self.logger.info(f"比较 {len(file_paths)} 个文件")
        
        comparison = await self.metadata_service.compare_files(file_paths)
        
        return {
            "success": True,
            "comparison": comparison
        }
    
    async def _export_metadata(self, data: Dict[str, Any], **kwargs) -> Dict[str, Any]:
        """导出元数据"""
        file_paths = data.get("file_paths", [])
        output_path = data.get("output_path")
        format_type = data.get("format", "json")
        
        if not file_paths:
            raise ValueError("未提供文件路径")
        if not output_path:
            raise ValueError("未提供输出路径")
        
        self.logger.info(f"导出 {len(file_paths)} 个文件的元数据到 {output_path}")
        
        result_path = await self.metadata_service.export_metadata(
            file_paths, output_path, format_type
        )
        
        return {
            "success": True,
            "output_path": result_path,
            "format": format_type,
            "file_count": len(file_paths)
        }
    
    async def _test_service(self) -> bool:
        """测试服务可用性"""
        try:
            # 创建一个临时的测试文件路径（不需要真实存在）
            # 只是测试服务是否正常初始化
            return self.metadata_service is not None
        except Exception as e:
            if hasattr(self.logger, 'error'):
                self.logger.error(f"服务测试失败: {e}")
            else:
                print(f"服务测试失败: {e}")
            return False
    
    # 插件生命周期方法
    def on_load(self) -> None:
        """插件加载时调用"""
        self.logger.info("元数据提取插件已加载")
    
    def on_unload(self) -> None:
        """插件卸载时调用"""
        self.logger.info("元数据提取插件已卸载")
    
    def on_enable(self) -> None:
        """插件启用时调用"""
        self.logger.info("元数据提取插件已启用")
    
    def on_disable(self) -> None:
        """插件禁用时调用"""
        self.logger.info("元数据提取插件已禁用")
    
    # AST处理方法（如果需要）
    def on_compiler(self, ast: Any, ctx: Any) -> Any:
        """编译时处理"""
        return ast
    
    def on_execute(self, ast: Any, ctx: Any) -> Any:
        """执行时处理"""
        return ctx
